// miniprogram/pages/pay/pay.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadParams = options;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.startPayment();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  


  /**
   * 开始支付
   */
  startPayment: function () {
    debugger
    let params = wx.parseJSONQueryStrObj(this.loadParams);
    let { nextLocation, succLocation, failLocation, timeStamp, ...payParams } = params;

    if (!succLocation || succLocation === "undefined" || succLocation === "null") {
      succLocation = nextLocation;
    }

    if (!failLocation || failLocation === "undefined" || failLocation === "null") {
      failLocation = nextLocation;
    }

    let payOpt = {
      timeStamp: timeStamp.toString(),
      ...payParams,
      success: (res) => {
        this.navToNextLocation(succLocation, res);
      },
      fail: (res) => {

        let errMsg = "支付失败:" + res.errMsg;

        wx.showToast({
          title: errMsg,
          icon: "none"
        });

        this.navToNextLocation(failLocation, res);
      }
    };


    wx.requestPayment(payOpt);
  },

  /**
   * 导航到下一个页面
   */
  navToNextLocation: function (nextLoca, info) {
    debugger
    if (nextLoca) {
      wx.letWebviewNavToInterLocat(nextLoca, "OutPage");
      let pageUrl = wx.stringifyUrl({
        url: "/pages/outPage/outPage",
        searchParams: {
          title: "支付结果"
        }
      });
      wx.redirectTo({
        url: pageUrl
      });
    } else {
      wx.navigateBack({
        delta: 1
      })
    }
  },
})